public ListNode mergeKLists(ListNode[] lists){ if (lists==null||lists.length==0)returnnull; if (lists.length<2)return lists[0]; ListNode dummy=new ListNode(-1); dummy.next=lists[0]; for (int i=1;i<lists.length;i++){ ListNode head=dummy,p=dummy.next,q=lists[i]; while (q!=null&&p!=null){ if (q.val< p.val){ head.next=q; q=q.next; }else { head.next=p; p=p.next; } head=head.next; } if (q!=null)head.next=q; if (p!=null)head.next=p; } return dummy.next; }
public ListNode mergeKLists(ListNode[] lists){ int len = lists.length; if (lists==null|| len ==0)returnnull; while (len>1){ for (int i=0;i<len/2;i++){ //中心对称,两两合并 lists[i]=mergeTwoList(lists[i],lists[len-1-i]); } len=(len+1)/2; } return lists[0]; } //合并两个链表 public ListNode mergeTwoList(ListNode l1,ListNode l2){ ListNode dummy=new ListNode(-1); ListNode head=dummy,p=l1,q=l2; while (p!=null&&q!=null){ if (p.val<q.val){ head.next=p; p=p.next; }else { head.next=q; q=q.next; } head=head.next; } if (q!=null)head.next=q; if (p!=null)head.next=p; return dummy.next; }